package devyouk.util.excel.listener;

import devyouk.util.excel.ColumnConfig;
import devyouk.util.excel.ExcelBuilder.OnCreateCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.RichTextString;
import devyouk.util.excel.cellAdapter.CellValueAdapter;

import javax.validation.constraints.NotNull;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class DefaultDataCellListener implements OnCreateCell {

    private CellValueAdapter cellAdapter;

    public void setAdapter(@NotNull CellValueAdapter cellAdapter) {
        this.cellAdapter = cellAdapter;
    }

    @Override
    public void onCreate(Cell prepared, int dataRowIndex, ColumnConfig columnConfig, List<?> dataSet) {
        Map<String, Object> dataRow = ((List<Map<String, Object>>) dataSet).get(dataRowIndex);
        Object dataObj = dataRow.get(columnConfig.getFieldName());
        CellValueAdapter adapter = columnConfig.getCellValueAdapter();
        if (adapter == null) {
            adapter = cellAdapter;
        }
        prepared.setCellType(adapter.getCellType());
        Object cellValue = adapter.getCellValue(dataObj);
        if (cellValue instanceof Double) {
            prepared.setCellValue((Double) dataObj);
        } else if (cellValue instanceof Date) {
            prepared.setCellValue((Date) dataObj);
        } else if (cellValue instanceof Boolean) {
            prepared.setCellValue((Boolean) dataObj);
        }  else if (cellValue instanceof Calendar) {
            prepared.setCellValue((Calendar) dataObj);
        } else if (cellValue instanceof RichTextString) {
            prepared.setCellValue((RichTextString) dataObj);
        } else {
            prepared.setCellValue(String.valueOf(cellValue));
        }
    }
}
